<template>
  <div class="w-full">
    <Card title="附言">
      <template #extra>
        <div>
          <a-button
            type="primary"
            class="mr-2"
            @click="isShowMsg = !isShowMsg"
            v-if="activeTimeKey != '2'"
            >{{ isShowMsg ? '收起' : '展开' }}</a-button
          >
          <a-button type="primary" @click="isShow = !isShow">回复</a-button>
        </div>
      </template>
      <div>
        <div>
          <template v-if="isShow">
            <a-textarea
              v-model:value="firstData.remark"
              placeholder="请输入回复"
              :auto-size="{ minRows: 3, maxRows: 5 }"
              class="custom-text"
              ref="textAreaRef"
            />
            <div class="flex justify-between mt-2 mb-3">
              <div class="flex">
                <Upload
                  :file-list="fileList"
                  :before-upload="(file) => beforeUpload(file, '1', {})"
                  @remove="(file) => handleRemove(file, '1', {})"
                  :multiple="true"
                >
                  <Button>
                    <UploadOutlined />
                    上传文件
                  </Button> </Upload
                ><span
                  class="ml-5 mt-1 text-blue-400 cursor-pointer"
                  style="font-size: 16px"
                  @click="selectUser"
                  >@用户</span
                >
              </div>
              <div>
                <!-- <Checkbox v-model:checked="firstData.isSecret">隐藏</Checkbox> -->
              </div>
              <div>
                <a-button class="custom-btn" @click="handleOk(firstData, -1)">确定</a-button>
              </div>
            </div>
          </template>
          <template v-if="isShowMsg && activeTimeKey != '2'">
            <div class="pt-2 pb-2" v-for="item in list" :key="item.id">
              <div class="w-full" style="border-bottom: #eee 1px solid">
                <div class="flex">
                  <div style="min-width: 86px">
                    <Tag
                      :color="item.color"
                      style="min-width: 70px; text-align: center; margin-bottom: 5px"
                      v-if="item.actionTitle"
                      >{{ item.actionTitle }}</Tag
                    >
                    <Tag
                      :color="item.color"
                      style="min-width: 70px; text-align: center; margin-bottom: 5px"
                      v-else
                      >- 无 -</Tag
                    >
                  </div>
                  <template v-if="!item.isLeaf">
                    <div style="color: #85c4f0" class="w-100px" :title="`${item.realName}`">{{
                      item.realName
                    }}</div>
                  </template>
                  <template v-if="item.isLeaf">
                    <div
                      style="color: #85c4f0"
                      class="text-right w-100px overflow-hidden"
                      :title="`${item.realName} 评论了 ${item.replyRealName}`"
                    >
                      {{ item.realName }}
                      <!-- 发表评论 {{ item.replyRealName }} -->
                    </div>
                  </template>
                  <div class="flex-1 pl-2 pr-2">
                    <div v-html="item.content"></div>
                    <template v-if="item.attachments && item.attachments.length">
                      <div v-for="(el, inAtt) in item.attachments" :key="`att${inAtt}`">
                        <a @click="handleDonwload(el)">{{ el.name }}</a>
                        <a @click="handlePreview(el)" title="预览" v-if="el.url" class="ml-3"
                          ><EyeOutlined style="color: rgba(28, 106, 235, 1)"
                        /></a>
                      </div>
                    </template>
                  </div>
                  <div>
                    <!-- <span class="cursor-pointer ml-2 mr-2" @click="handleDel(item.id)">删除</span> -->
                    {{ item.addDate }}
                    <span class="cursor-pointer mr-2"
                      ><Icon
                        style="color: #ed6f6f"
                        title="删除"
                        icon="ant-design:delete-outlined"
                        v-if="isFlowManager"
                        @click="handleDel(item.id)"
                    /></span>
                    <span
                      class="cursor-pointer"
                      v-if="flowStatus == 1"
                      :style="{ visibility: item.parentId == -1 ? 'visible' : 'hidden' }"
                    >
                      <Icon
                        style="color: #ffc24d"
                        icon="ant-design:message-outlined"
                        @click="item.show = !item.show"
                      />
                    </span>
                  </div>
                </div>
                <div class="mt-2 mb-2" v-if="item.show && item.parentId == -1">
                  <a-textarea
                    v-model:value="item.remark"
                    placeholder="请输入回复"
                    :auto-size="{ minRows: 2, maxRows: 3 }"
                    class="custom-text"
                  />
                  <div class="mt-2">
                    <Upload
                      :file-list="item.fileList"
                      :before-upload="(file) => beforeUpload(file, '2', item)"
                      @remove="(file) => handleRemove(file, '2', item)"
                      :multiple="true"
                    >
                      <Button>
                        <UploadOutlined />
                        上传文件
                      </Button>
                    </Upload>
                  </div>
                  <div class="flex justify-between mt-2">
                    <div>
                      <Checkbox v-model:checked="item.isSecret">隐藏</Checkbox>
                    </div>
                    <div>
                      <a-button
                        class="custom-btn"
                        @click="handleOk(item, item.isLeaf ? item.parentId : item.id)"
                        >确定</a-button
                      >
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </template>
        </div>
      </div>
    </Card>
    <SelectUser @register="registerModal" @success="handleCallBack" />
  </div>
</template>
<script lang="ts">
  import { defineComponent, ref, unref, watchEffect, h } from 'vue';
  import { Card, Checkbox, UploadProps, Upload, Button, Tag } from 'ant-design-vue';
  import Icon from '/@/components/Icon/index';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { dateUtil as dayjs } from '/@/utils/dateUtil';
  import { downloadByUrl } from '/@/utils/file/download';
  import {
    getListAnnex,
    getAddReply,
    getDelAnnex,
    getDownloadAnnexAttachment,
  } from '/@/api/process/process';
  import { UploadOutlined, EyeOutlined } from '@ant-design/icons-vue';
  import { useUserStore } from '/@/store/modules/user';
  import { colorList } from '/@/views/system/workflow/flowManagement/modules/flowPicture/modules/modules/nodeEdit/nodeEdit.data';
  import { SelectUser } from '/@/components/CustomComp';
  import { useModal } from '/@/components/Modal';

  export default defineComponent({
    components: {
      Card,
      Checkbox,
      Icon,
      Upload,
      UploadOutlined,
      Button,
      EyeOutlined,
      Tag,
      SelectUser,
    },
    props: {
      flowInfo: {
        type: Object,
        default: () => {
          return {};
        },
      },
      activeTimeKey: {
        type: String,
        default: '1',
      },
    },
    emits: ['success', 'register'],
    setup(props, { emit }) {
      const { createMessage, createConfirm } = useMessage();
      const userStore = useUserStore();
      const serverInfo = userStore.getServerInfo;
      const list = ref<Recordable[]>([]);
      const fileList = ref<any>([]);
      const firstData = ref<Recordable>({
        remark: '',
        isSecret: false,
      });
      const isShow = ref(false);
      const isShowMsg = ref(true);
      const isFlowManager = ref(false);
      const flowStatus = ref(1); // 流程状态，默认为处理中
      const textAreaRef = ref(null);

      // 高亮处理函数
      function highlightMentions(text) {
        // 转义 HTML 特殊字符
        const escapedText = text.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');

        // 使用智能匹配规则
        return escapedText.replace(/@[\w\u00C0-\uFFFF-]+/g, (match, offset, str) => {
          // 排除 email 情况（前一个字符是单词字符）
          if (offset > 0 && /[\w-]/.test(str[offset - 1])) {
            return match;
          }
          return `<span class="mention text-blue-400">${match}</span>`;
        });
      }

      const fetch = () => {
        getListAnnex({ flowId: props?.flowInfo?.flowId }).then((res) => {
          console.log('getListAnnex res', res);
          list.value = [];
          setChild(res);
          console.log('list.value', list.value);
        });
      };
      const setChild = (data: Recordable, isLeaf = false) => {
        if (data?.length) {
          data.forEach((item) => {
            item.addDate = dayjs(item.addDate).format('YY-MM-DD HH:mm');
            item.isSecret = item.show = false;
            item.isLeaf = isLeaf;
            if (item.attachments && item.attachments.length) {
              item.attachments.forEach((el) => {
                const path = el.visualPath + '/' + el.diskName;
                el.url = path
                  ? serverInfo.rootPath + (path && path.startsWith('/') ? path : `/${path}`)
                  : '';
              });
            }
            item.fileList = [];

            const it = colorList.find((colorItem) => colorItem.id == item.actionColorIndex);
            if (it) {
              item.color = it.color;
            }

            item.content = highlightMentions(item.content);

            list.value.push(item);
            if (item.aryAnnexSub?.length) {
              setChild(item.aryAnnexSub, true);
            }
          });
        }
      };
      const search = () => {
        list.value = [];
        fileList.value = [];
        fetch();
      };
      watchEffect(() => {
        props?.flowInfo?.flowId && search();
        console.log('props?.flowInfo', props?.flowInfo);
        isFlowManager.value = props.flowInfo.isFlowManager;
        flowStatus.value = props.flowInfo.flowStatus;
      });
      const handleOk = (record: Recordable, parentId: number) => {
        console.log('props', props.flowInfo, 'record', record);
        let params = {
          flowId: props.flowInfo.flowId,
          myActionId: props.flowInfo.myActionId || '-1',
          parentId: parentId,
          content: record.remark,
          isSecret: record.isSecret ? 1 : 0,
          progress: 0,
        };
        if (!params.content) {
          createMessage.warning('回复内容不能为空');
          return;
        }
        console.log('params', params);
        const formData = new FormData();
        for (let v in params) {
          formData.append(v, params[v]);
        }
        let files: any = [];
        if (parentId == -1) {
          files = [...fileList.value];
        } else {
          files = [...record.fileList];
        }
        if (files.length) {
          files.forEach((item) => {
            formData.append('files', item);
          });
        }
        getAddReply(formData).then((res) => {
          console.log('res==>', res);
          emit('success');
          search();
          notShow();
        });
      };

      const notShow = () => {
        isShow.value = false;
        firstData.value.remark = '';
        firstData.value.isSecret = false;
      };

      const handleDel = (id: number) => {
        createConfirm({
          iconType: 'warning',
          title: () => h('span', '您确定要删除么？'),
          onOk: async () => {
            await del(id);
          },
        });
      };
      const del = async (id: number) => {
        await getDelAnnex({ id });
        search();
      };

      // -----------------------------------------------------文件上传开始-------------------------------------------------------------
      //上传前校验
      const beforeUpload = (file, type, record) => {
        if (type == '2') {
          record.fileList = [...record.fileList, file];
          list.value = [...list.value];
        } else {
          fileList.value = [...fileList.value, file];
        }
        return false;
      };
      // 上传文件删除
      const handleRemove = (file, type, record) => {
        if (type == '2') {
          const index = record.fileList.indexOf(file);
          const newFileList = record.fileList.slice();
          newFileList.splice(index, 1);
          record.fileList = newFileList;
          list.value = [...list.value];
        } else {
          const index = fileList.value.indexOf(file);
          const newFileList = fileList.value.slice();
          newFileList.splice(index, 1);
          fileList.value = newFileList;
        }
      };

      //下载
      const handleDonwload = (record) => {
        if (record.url) {
          downloadByUrl({ url: record.url, fileName: record.name });
        }
      };
      const handlePreview = (record: any) => {
        if (record.url) {
          const type = record.url.split('.').pop();
          if ('png|PNG|jpg|JPG|jpeg|JPEG|'.includes(type)) {
            window.open(record.url);
          } else if ('doc|DOC|docx|DOCX'.includes(type)) {
            preview('https://view.officeapps.live.com/op/view.aspx?src=' + record.url);
          } else {
            preview(record.url);
          }
        }
      };
      // -----------------------------------------------------文件上传结束-------------------------------------------------------------

      const [registerModal, { openModal }] = useModal();
      function selectUser() {
        let users = [];
        openModal(true, {
          isUpdate: false,
          users: users,
        });
      }

      //人员组件选择后回调
      async function handleCallBack(data) {
        console.log('handleCallBack', data);

        let datas = data;
        let atUsers = '';
        datas.forEach((item) => {
          if (atUsers == '') atUsers = ' @' + item.loginName + '  ';
          else atUsers += '@' + item.loginName + '  ';
        });

        // 获取文本区域元素
        const textarea = textAreaRef.value?.$el;
        if (!textarea) return;

        console.log('textarea', textarea);

        // 获取光标位置
        const startPos = textarea.selectionStart;
        const endPos = textarea.selectionEnd;

        // 保存当前光标之前的文本
        const beforeText = textarea.value.substring(0, startPos);
        // 保存当前光标之后的文本
        const afterText = textarea.value.substring(endPos, textarea.value.length);

        // 在光标位置插入文本
        textarea.value = beforeText + atUsers + afterText;

        // 更新光标位置到插入文本的末尾
        textarea.selectionStart = startPos + atUsers.length;
        textarea.selectionEnd = startPos + atUsers.length;

        firstData.value.remark = textarea.value;
      }

      return {
        firstData,
        isShow,
        handleOk,
        list,
        handleDel,
        isShowMsg,
        isFlowManager,
        flowStatus,
        beforeUpload,
        handleRemove,
        fileList,
        handlePreview,
        handleDonwload,
        registerModal,
        selectUser,
        handleCallBack,
        textAreaRef,
      };
    },
  });
</script>

<style lang="less" scoped>
  :deep(.ant-card-head-title) {
    font-weight: bold;
  }
  .custom-text {
    border: solid 1px #ffa200;
    &:focus {
      border: solid 1px #0960bd;
    }
  }
  .custom-btn {
    background-color: #ffc24d;
    color: #fff;
  }
</style>
